import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'flutter_communication.dart';

/// Flutter通讯工具类使用示例
///
/// 展示如何使用FlutterCommunication类进行各种通讯操作
class CommunicationExample {
  
  /// 示例1: 获取设备信息
  static Future<void> exampleGetDeviceInfo() async {
    try {
      final deviceInfo = await FlutterCommunication.getDeviceInfo();
      print('Device Info: $deviceInfo');
    } catch (e) {
      print('Error getting device info: $e');
    }
  }

  /// 示例2: 获取用户列表
  static Future<void> exampleGetUsers() async {
    try {
      final users = await FlutterCommunication.getUsers();
      print('Users count: ${users.length}');
      for (var user in users) {
        print('User: ${user['name']} - ${user['email']}');
      }
    } catch (e) {
      print('Error getting users: $e');
    }
  }

  /// 示例3: 添加用户
  static Future<void> exampleAddUser() async {
    try {
      final userData = {
        'name': 'Test User',
        'email': 'test@example.com',
        'phone': '+1234567890',
        'createdAt': DateTime.now().toIso8601String(),
      };

      final success = await FlutterCommunication.addUser(userData);
      print('Add user success: $success');
    } catch (e) {
      print('Error adding user: $e');
    }
  }

  /// 示例4: 监听原生事件
  static void exampleListenToEvents() {
    FlutterCommunication.nativeEvents.listen((event) {
      print('Received event: $event');
      
      if (event is Map) {
        final eventType = event['type'];
        final timestamp = event['timestamp'];
        
        switch (eventType) {
          case 'userUpdated':
            print('User data updated at: $timestamp');
            // 可以在这里刷新UI或执行其他操作
            break;
          case 'networkChanged':
            print('Network status changed at: $timestamp');
            break;
          default:
            print('Unknown event type: $eventType');
        }
      }
    });
  }

  /// 示例5: 发送数据到原生
  static Future<void> exampleSendDataToNative() async {
    try {
      await FlutterCommunication.sendDataToNative('Hello from Flutter!');
      print('Data sent to native successfully');
    } catch (e) {
      print('Error sending data to native: $e');
    }
  }

  /// 示例6: 显示原生Toast
  static Future<void> exampleShowNativeToast() async {
    try {
      await FlutterCommunication.showNativeToast('This is a test message');
      print('Toast message sent');
    } catch (e) {
      print('Error showing toast: $e');
    }
  }

  /// 示例7: 获取系统信息
  static Future<void> exampleGetSystemInfo() async {
    try {
      final systemInfo = await FlutterCommunication.getSystemInfo();
      print('System Info: $systemInfo');
    } catch (e) {
      print('Error getting system info: $e');
    }
  }

  /// 示例8: 检查通讯状态
  static Future<void> exampleCheckCommunicationStatus() async {
    try {
      final status = await FlutterCommunication.getCommunicationStatus();
      print('Communication Status: $status');
    } catch (e) {
      print('Error checking communication status: $e');
    }
  }

  /// 示例9: 完整的用户管理流程
  static Future<void> exampleCompleteUserManagement() async {
    try {
      // 1. 检查通讯状态
      final isAvailable = await FlutterCommunication.isCommunicationAvailable();
      if (!isAvailable) {
        print('Communication not available');
        return;
      }

      // 2. 获取当前用户列表
      final users = await FlutterCommunication.getUsers();
      print('Current users: ${users.length}');

      // 3. 添加新用户
      final newUser = {
        'name': 'New User',
        'email': 'newuser@example.com',
        'phone': '+9876543210',
        'createdAt': DateTime.now().toIso8601String(),
      };

      final addSuccess = await FlutterCommunication.addUser(newUser);
      print('Add user success: $addSuccess');

      // 4. 获取更新后的用户列表
      final updatedUsers = await FlutterCommunication.getUsers();
      print('Updated users: ${updatedUsers.length}');

      // 5. 发送通知到原生
      await FlutterCommunication.sendDataToNative('User management completed');

    } catch (e) {
      print('Error in user management: $e');
    }
  }

  /// 示例10: 错误处理最佳实践
  static Future<void> exampleErrorHandling() async {
    try {
      // 尝试调用可能不存在的方法
      final result = await FlutterCommunication.callNativeMethod('nonExistentMethod');
      if (result == null) {
        print('Method not implemented or failed');
      }
    } on PlatformException catch (e) {
      print('Platform exception: ${e.message}');
    } catch (e) {
      print('Unexpected error: $e');
    }
  }
}

/**
 * 通讯工具类在Widget中的使用示例
 */
class CommunicationWidgetExample extends StatefulWidget {
  @override
  _CommunicationWidgetExampleState createState() => _CommunicationWidgetExampleState();
}

class _CommunicationWidgetExampleState extends State<CommunicationWidgetExample> {
  String _deviceInfo = 'Loading...';
  List<Map<String, dynamic>> _users = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadData();
    _setupEventListeners();
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final deviceInfo = await FlutterCommunication.getDeviceInfo();
      final users = await FlutterCommunication.getUsers();

      setState(() {
        _deviceInfo = deviceInfo;
        _users = users;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _deviceInfo = 'Error: $e';
        _isLoading = false;
      });
    }
  }

  void _setupEventListeners() {
    FlutterCommunication.nativeEvents.listen((event) {
      if (event is Map && event['type'] == 'userUpdated') {
        // 用户数据更新时重新加载
        _loadData();
      }
    });
  }

  Future<void> _addTestUser() async {
    try {
      final userData = {
        'name': 'Test User ${DateTime.now().millisecondsSinceEpoch}',
        'email': 'test${DateTime.now().millisecondsSinceEpoch}@example.com',
        'phone': '+1234567890',
        'createdAt': DateTime.now().toIso8601String(),
      };

      final success = await FlutterCommunication.addUser(userData);
      
      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('User added successfully!')),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to add user')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Communication Example'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _loadData,
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Card(
                  margin: EdgeInsets.all(16),
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Device Info',
                          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                        SizedBox(height: 8),
                        Text(_deviceInfo),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: _users.length,
                    itemBuilder: (context, index) {
                      final user = _users[index];
                      return ListTile(
                        title: Text(user['name'] ?? 'Unknown'),
                        subtitle: Text(user['email'] ?? ''),
                      );
                    },
                  ),
                ),
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addTestUser,
        child: Icon(Icons.add),
        tooltip: 'Add Test User',
      ),
    );
  }
} 